import Taro,{Component} from "@tarojs/taro"
import styles from './index.module.scss'
import { View, Image, OpenData, Switch} from "@tarojs/components"
import { AtIcon } from 'taro-ui'
import { filter, dialog } from '@/util/index'
import {getPersonalInfo, checkSign, autoAcceptOrder} from '@/api/index'
import ServiceOnline from '@/components/ServiceOnline'

import INFOBG_IMG from '@/assets/img/grzx_pic_bj.png'
import DEFAULT_AVATAR from '@/assets/img/personal_avatar.png'
import PERSONAL_PROTOCOL from '@/assets/img/personal_protocol.png'
import { connect } from "@tarojs/redux"
import { setUrl } from "@/actions/web"

@connect(({user}) => ({
  info: user.info,
  isSign: user.isSign
}), dispatch => ({
  setUrl: (data) => dispatch(setUrl(data))
}))
class Personal extends Component {
  config = {
    navigationBarTitleText: '个人中心'
  }

  state = {
    total: '',
    signText: '已实名',
    isAutoAccept: 0,
    visibleDialog: false
  }

  constructor(props) {
    super(props)
  }

  componentWillMount = () => {}

  componentDidShow = () => {
    this.getPersonalInfo()
  }

  getPersonalInfo = async () => {
    const { info, isSign } = this.props
    if (isSign) {
      try {
        const { mobile } = info
        const { data } = await getPersonalInfo({loginAccount: mobile})
        this.setState({total: data.performanceFee.toFixed(2), signText: data.realName, isAutoAccept: !!data.isAutoMerchantTask})
      } catch(e) {
        Taro.showToast({title: e.message, icon: 'none'})
      }
    } else {
      Taro.reLaunch({url: '/pages/home/index'})
    }
  }

  goName = (item) =>{
    const { setUrl } = this.props
    // if (item.id === 2) {
      // this.checkSign()
    // } else {
      Taro.navigateTo({url: item.url})
    // }
  }

  checkSign = async () => {
    const { setUrl, info } = this.props
    const { mobile } = info
    try {
      Taro.showLoading({title: '', mask: true})
      const { data, code } = await checkSign({loginAccount: mobile})
      Taro.hideLoading()
      if (code) {
        Taro.navigateTo({url: '/pages/preview/index'})
      } else {
        setUrl(data.url)
        Taro.navigateTo({url: '/pages/web/index'})
      }
    } catch(e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  async handleChange() {
    this.setState({visibleDialog: true})
  }

  async toggleAutoAccept() {
    try {
      const { info } = this.props
      await autoAcceptOrder({loginAccount: info.mobile, isAutoMerchantTask: +!this.state.isAutoAccept})
      this.setState(pre => ({isAutoAccept: !pre.isAutoAccept, visibleDialog: false}))
    } catch (e) {
      dialog.toast({title: e.message})
    }
  }

  render () {
    const { info } = this.props
    const { total, signText, isAutoAccept, visibleDialog } = this.state
    const userList=[
      {id: 0, name:'收益记录', icon: 'sign', height: 32, url:'/pages/cheques/index', active: true},
      {id: 1, name:'个人信息', icon: 'user', height: 36, url:'/pages/user/index', active: true},
      {id: 2, name:'签约信息', icon: 'edit', height: 35, url:'/pages/contractList/index', active: true},
      {id: 6, name:'培训课程', icon: 'sign', height: 32, url:'/pages/lessonRecord/index', active: true},
      {id: 5, name:'我的证书', icon: 'task', height: 35, url:'/pages/certificate/index', active: true},
      {id: 4, name:'个人履历', icon: 'task', height: 35, url:'/pages/resume/index', active: true},
      {id: 3, name:'任务列表', icon: 'task', height: 35, url:'/pages/taskList/index', active: false},
      {id: 7, name:'用工计算工具', icon: 'square', height: 35, url:'/pages/employComputed/index', active: true}
    ]
    return (
      <View className={styles.Wrapper}>
        <View className={styles.container}>
          <View className={styles.head}>
            <View className={styles.photo}>
              <OpenData type="userAvatarUrl" default-avatar={DEFAULT_AVATAR}></OpenData>
            </View>
            <View className={styles.telInfo}>
              {info && <View className={styles.tel}> {filter.formatPhone(info.mobile)}</View>}
              <View className={styles.sign}> {signText}</View>
            </View>
          </View>
          <View className={styles.moneyWrap}>
            <Image src={INFOBG_IMG} className={styles.moneyImg}></Image>
            <View className={styles.title}> 您在椰云众包平台获得的历史总收益（元）</View>
            <View className={styles.money}> {total}</View>
          </View>
          <View className={styles.listWrap}>
            {
              userList.map((item)=>{
                if (item.active) {
                  return (
                    <View className={styles.list} onClick={() => this.goName(item)} key={item.id + ''}>
                      <View className={styles.name}>
                        <Image src={`/assets/img/personal_${item.icon}.png`} className={styles.icon} style={`height: ${item.height}rpx`}></Image>
                        {item.name}
                      </View>
                      <AtIcon value='iconfont icon-right' size='18' color='#757575'></AtIcon>
                    </View>
                  )
                }
              })
            }
          </View>
          <View className={styles.autoAccept}>
            <View className={styles.text}>自动接单</View>
            <Switch color='#22ADF7' checked={isAutoAccept} />
            <View className={styles.switchMask} onClick={ !isAutoAccept ? this.handleChange : this.toggleAutoAccept}></View>
          </View>
        </View>
        <View className={styles.footer}>
          <Image src={PERSONAL_PROTOCOL} className={styles.protocolImg}></Image>
          <View className={styles.protocol}>椰云众包会保障您的隐私安全，感谢您辛勤的工作</View>
        </View>
        <View className={styles.serviceOnline}>
          <ServiceOnline/>
        </View>
        {
          visibleDialog 
          && 
          <View className={styles.mask}>
            <View className={styles.autoAccept}>
              <View className={styles.subtitle}>开启自动接单</View>
              <View className={styles.article}>“自动接单”功能针对任务广场里的任务，开启该功能后，会进行自动接任务到我的任务栏里；</View>
              <View className={styles.article}>平台有部分任务，商户设置了必需要签署用工协议才能接单，因此该部分任务无法使用该功能；</View>
              <View className={styles.article}>如“多人接单”的，则平台将通过接单者过往的接单记录等，自动提示是否接单成功</View>
              <Button className={styles.confirm} onClick={this.toggleAutoAccept}>同意并开启</Button>
              <View className={styles.cancel}>
                <Text onClick={() => this.setState({visibleDialog: false})}>取消</Text>
              </View>
            </View>
          </View>
        }
      </View>
    )
  }
}

export default Personal
